﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using BrnMall.Business;
using BrnMall.Manager.Domain.WeApp;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.Sdk.WeiXin;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Util;
using BrnMall.WeiXin.Sdk;
using Newtonsoft.Json;
using Tencent;
using BrnMall.Manager.Manager.Store;
using BrnMall.Services;

namespace BrnMall.Web.StoreAdmin.controllers
{
    public class WeChatNotifyController : BaseController
    {
        /// <summary>
        /// 授权登录相关
        /// 授权事件接收URL
        /// </summary>
        /// <returns></returns>
        public ActionResult TicketNotify(string timestamp, string nonce, string msg_signature, string encrypt_type)
        {
            byte[] data = Request.BinaryRead(Request.TotalBytes);
            string postData = Encoding.Default.GetString(data);
            var resultXml = string.Empty;
            var platform = WeApplicationManager.GetDefaultApplicationPlatform();
            if (platform == null) return Content("false");
            var decryptMsg = new WXBizMsgCrypt(platform.Token, platform.AESKey, platform.AppId);
            decryptMsg.DecryptMsg(msg_signature, timestamp, nonce, postData, ref resultXml);
            var resHandler = new ResponseHandler(resultXml);
            var appId = resHandler.getParameter("AppId")??"";
            var infoType = resHandler.getParameter("InfoType")??"";
            if (infoType.Equals("component_verify_ticket", StringComparison.InvariantCultureIgnoreCase))
            {
                var componentVerifyTicket = resHandler.getParameter("ComponentVerifyTicket");
                if (!appId.Equals(platform.AppId, StringComparison.InvariantCultureIgnoreCase))
                    return Content("false");
                platform.ComponentVerifyTicket = componentVerifyTicket;
                WeApplicationManager.UpdateComponentVerifyTicket(platform.Id, componentVerifyTicket);
                RefreshPreAuthCode();
            }else if (infoType.Equals("unauthorized", StringComparison.InvariantCultureIgnoreCase))
            {
                var authorizerAppid = resHandler.getParameter("AuthorizerAppid");
                var auth = AppAuthorizationManager.GetAppAuthorizationByAppId(authorizerAppid);
                AppAuthorizationManager.DeleteAuth(auth.Id);
            }
            return Content("success");
        }

        private static void RefreshPreAuthCode()
        {
            var platform = WeApplicationManager.GetDefaultApplicationPlatform();
            if (platform.Component_Expires_In.Year == 1900 ||(platform.Component_Expires_In.Year != 1900&& platform.Component_Expires_In.Subtract(DateTime.Now).TotalMinutes < 10))//有效期2小时
            {
                var postData = new ComponentAccessTokenPostData
                {
                    component_appid = platform.AppId,
                    component_appsecret = platform.AppSecret,
                    component_verify_ticket = platform.ComponentVerifyTicket
                };
                var componetAccessToken = WeiXinSdk.GetComponentAccessTokenResponse(postData);
                if (componetAccessToken != null)
                {
                    platform.Component_Access_Token = componetAccessToken.component_access_token;
                    platform.Component_Expires_In = DateTime.Now.AddSeconds(componetAccessToken.expires_in);
                    WeApplicationManager.UpdateComponentAccessToken(platform.Id, platform.Component_Access_Token, platform.Component_Expires_In);
                }
            }
            var preAuthCode = WeiXinSdk.GetPreAuthCodeResponse(platform.AppId, platform.Component_Access_Token);
            if (preAuthCode != null)
            {
                WeApplicationManager.UpdatePreAuthCode(platform.Id, preAuthCode.pre_auth_code, DateTime.Now.AddSeconds(preAuthCode.expires_in));
            }
        }

        /// <summary>
        /// 绑定模板程序
        /// </summary>
        /// <param name="storeappid"></param>
        /// <returns></returns>
        public ActionResult ApplicationBind(int storeappid)
        {
            RefreshPreAuthCode();
            var plateform = WeApplicationManager.GetDefaultApplicationPlatform();
            if (string.IsNullOrEmpty(plateform?.Pre_Auth_Code))
                return Content("获取预授权码错误");
            var redirectUri = $"https://weadmin.711688.net.cn/storeadmin/wechatnotify/AuthBack?storeappid={storeappid}";
            var url =
                $"https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={plateform.AppId}&pre_auth_code={plateform.Pre_Auth_Code}&redirect_uri={redirectUri}&auth_type=2";
            return Redirect(url);
        }

        public ActionResult AuthBack(string auth_code, int expires_in, int storeappid)
        {
            try
            {
                LogUtil.WriteLog($"{auth_code}-{expires_in}-{storeappid}");
                var plateform = WeApplicationManager.GetDefaultApplicationPlatform();
                var result = WeiXinSdk.GetAuthorization(plateform.Component_Access_Token, plateform.AppId, auth_code);
                if (result?.authorization_info?.authorizer_appid == null) return Content("授权失败");
                var storewxapp = StoreWxAppManager.GetStoreWxAppByAppId(result.authorization_info.authorizer_appid);
                if (storewxapp != null)
                {
                    var storeInfo = Stores.GetStoreById(storewxapp.StoreId);
                    return Content($"本次创建小程序不成功！您的小程序账号在店铺{storeInfo.Name},ID:{storeInfo.StoreId}中已经存在");
                }
                var oldAuth = AppAuthorizationManager.GetAppAuthorizationByAppId(result.authorization_info.authorizer_appid);
                if (oldAuth != null)
                {
                    var oldstoreApp = StoreApplicationManager.GetStoreApplicationByAuthId(oldAuth.Id);
                    if (oldstoreApp!=null)
                        return Content($"本次创建小程序不成功！您的小程序账号已经成功授权过，并创建“{oldstoreApp.Name}”，请勿重复授权同一个小程序");
                }
                var authInfo = WeiXinSdk.GetAuthorizationInfo(plateform.Component_Access_Token, plateform.AppId,
                result.authorization_info.authorizer_appid);
                if (authInfo == null)
                    return Content("获取授权人基本信息失败");
                var auth = new AppAuthorization
                {
                    Authorizer_Access_Token = result.authorization_info.authorizer_access_token,
                    Authorizer_Appid = result.authorization_info.authorizer_appid,
                    Authorizer_Refresh_Token = result.authorization_info.authorizer_refresh_token,
                    Expires_In = DateTime.Now.AddSeconds(result.authorization_info.expires_in),
                    Head_Img = authInfo.authorizer_info.head_img??"",
                    Nick_Name = authInfo.authorizer_info.nick_name??"",
                    Principal_Name = authInfo.authorizer_info.principal_name??"",
                    Qrcode_Url = authInfo.authorizer_info.qrcode_url??"",
                    Service_Type_Info = authInfo.authorizer_info.service_type_info.id,
                    Signature = authInfo.authorizer_info.signature??"",
                    User_Name = authInfo.authorizer_info.user_name??"",
                    Verify_Type_Info = authInfo.authorizer_info.verify_type_info.id
                };
                var domainResult = WeAppSdk.SetDomain(auth.Authorizer_Access_Token, "weapp.711688.net.cn");
                if (domainResult.errcode > 0)
                    return Content($"设置服务器域名失败:{domainResult.errmsg}");
                AppAuthorizationManager.AddAuth(auth);
                var application = StoreApplicationManager.GetStoreApplication(storeappid);
                if (application == null) return Content($"小程序{storeappid}不存在");
                application.AuthorizationId = auth.Id;
                application.Logo = auth.Head_Img;
                application.Name = auth.Nick_Name;
                StoreApplicationManager.UpdateStoreApplication(application);
                return Content($"授权成功，请执行下一步操作");
                //return RedirectToAction("StoreAppList", "WeApp");

            }
            catch (Exception e)
            {
                LogUtil.WriteLog(e.Message);
                LogUtil.WriteLog(e.StackTrace);
                throw;
            }

        }
        /// <summary>
        /// 消息与事件接收URL
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        public ActionResult CallbackNotify(string appid,string signature,string timestamp,string nonce,string msg_signature)
        {
            //byte[] data = Request.BinaryRead(Request.TotalBytes);
            //string postData = Encoding.Default.GetString(data);
            //var resultXml = string.Empty;
            //var platform = WeApplicationManager.GetDefaultApplicationPlatform();
            //if (platform == null) return Content("false");
            //var decryptMsg = new WXBizMsgCrypt(platform.Token, platform.AESKey, platform.AppId);
            //decryptMsg.DecryptMsg(msg_signature, timestamp, nonce, postData, ref resultXml);
            //var resHandler = new ResponseHandler(resultXml);
            //var rawappid = appid.TrimStart('/');
            //var eventInfo=resHandler.getParameter("Event") ??"";
            //var reason = resHandler.getParameter("Reason") ?? "";
            //var storeApplication = StoreApplicationManager.GetStoreApplicationsByWeChatAppId(rawappid);
            //if (storeApplication == null)
            //{
            //    LogUtil.WriteLog($"未找打对应的小程序授权信息{rawappid}");
            //    return Content("fail");
            //}
            //if (eventInfo.Equals("weapp_audit_fail"))
            //{
            //    storeApplication.AuditInfo = reason;
            //    storeApplication.DevStatus = 2;
            //}
            //else
            //{
            //    storeApplication.AuditInfo = "";
            //    storeApplication.DevStatus = 4;
            //    StoreApplicationManager.UpdateStoreApplication(storeApplication);
            //    StoreAppReleaseManager.ReleaseStoreApp(storeApplication.StoreAppId);
            //}
            //LogUtil.WriteLog($"CallbackNotify:{resultXml}");
            //LogUtil.WriteLog($"CallbackNotify:{rawappid}");
            return Content("fail");
        }
    }
}
